package com.jackeysun.log

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import android.hardware.SensorEventListener
import android.hardware.SensorEvent
import com.jackeysun.common.go
import com.jackeysun.log.SensorHelper

/**
 * Created by sunxunchao on 2020/1/13
 */
class SensorHelper(private val context: Context) {
    private var sensorAccelerometer: Sensor? = null
    private val sm: SensorManager?
    private val sensorEventListener: SensorEventListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]
            //            Log.d(TAG, "onSensorChanged:" + "x=" + x + "y=" + y + "z=" + z);
            if (Math.abs(x) + Math.abs(y) + Math.abs(z) > 40) {
                context.go(LogFileActivity())
            }
        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
    }

    companion object {
        private val TAG = SensorHelper::class.java.simpleName
    }

    init {
        sm = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        if (sm != null) {
            sensorAccelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
            if (sensorAccelerometer != null) {
                sm.registerListener(
                    sensorEventListener,
                    sensorAccelerometer,
                    SensorManager.SENSOR_DELAY_NORMAL
                )
            }
        }
    }
}